package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Service
public class AuthService {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private UserClient userClient;

    public void login(String username, String password, HttpServletResponse response) {
        // 	1.远程调用ly-user，验证用户名和密码
        UserDTO user = null;
        try {
            user = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        //	2.判断用户查询是否成功
        if (user == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        // 3.利用私钥生成JWT
        // 3.1.封装用户信息
        UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), "guest");
        // 3.2.生成token
        String token = JwtUtils.generateTokenExpireInMinutes(
                userInfo, prop.getPrivateKey(), prop.getUser().getExpireMinutes());

        // 4.把JWT写到用户cookie
        writeCookie(response, token);
    }

    private void writeCookie(HttpServletResponse response, String token) {
        CookieUtils.newCookieBuilder()
                .name(prop.getUser().getCookieName()).value(token)
                .domain(prop.getUser().getDomain())
                .httpOnly(true)
                .response(response)
                .build();
    }

    public UserInfo verify(HttpServletRequest request, HttpServletResponse response) {
        // 1.服务端获取cookie中的token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        // 2.校验token
        if (StringUtils.isBlank(token)) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        // 3.解析token，获取用户信息
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            // 说明token解析失败！
            throw new LyException(ExceptionEnum.UNAUTHORIZED, e);
        }
        // 4.黑名单校验
        String id = payload.getId();
        Boolean isExists = redisTemplate.hasKey(id);
        if (BooleanUtils.isTrue(isExists)) {
            // token无效
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }

        // 5.刷新token
        // 5.1.获取剩余有效期
        Date expiration = payload.getExpiration();
        long remainTime = expiration.getTime() - System.currentTimeMillis();
        // 5.2.判断是否达到刷新的阈值
        if (remainTime < prop.getUser().getTokenRefreshThresold()) {
            // 5.3.刷新token
            token = JwtUtils.generateTokenExpireInMinutes(
                    payload.getUserInfo(), prop.getPrivateKey(), prop.getUser().getExpireMinutes());
            // 5.4.写到cookie
            writeCookie(response, token);
        }
        // 6.返回
        return payload.getUserInfo();
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.获取cookie中的token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        // 2.解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            // 说明token解析失败！
            throw new LyException(ExceptionEnum.UNAUTHORIZED, e);
        }
        // 3.获取tokenId，及剩余时间
        String id = payload.getId();
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();

        // 4.记录tokenId到Redis中，以token剩余时间作为过期时间，是一个黑名单
        redisTemplate.opsForValue().set(id, "1", remainTime, TimeUnit.MILLISECONDS);

        // 5.删除cookie（重新写cookie,maxAge=0）
        CookieUtils.deleteCookie(
                prop.getUser().getCookieName(), prop.getUser().getDomain(), response);
    }
}
